<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/5/7
 * Time: 14:25
 */

namespace zhtfrontend\controllers;

use common\components\helpers\Tree;
use common\models\datas\Cate;
use doumiaoduo\buildform\BuildForm;
use zhtfrontend\components\bases\BaseController;
use common\components\helpers\Fun;
use zhtfrontend\models\datas\Admin;
use zhtfrontend\models\datas\CateRelation;
use zhtfrontend\models\datas\Headmaster;
use zhtfrontend\models\datas\Mechanic;
use zhtfrontend\models\datas\NavMenu;
use zhtfrontend\models\datas\Teacher;
use zhtfrontend\models\forms\TeacherSearchForm;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use common\components\actions\DeleteAction;
use yii\web\BadRequestHttpException;
use common\models\datas\Site;
use yii\web\Response;
use yii\widgets\ActiveForm;

class TeacherController extends BaseController
{
    public function actionIndex()
    {
        $mids = Fun::getMechanicIds();
        $search_form = new TeacherSearchForm();
        if (\Yii::$app->request->isPost) {
            $search_form->load(\Yii::$app->request->post());
        }
        $search_data = array_filter($search_form->attributes);
        $teacher = Teacher::find()->where(['status'=>1])->orderBy('mechanic_id ASC');
        if (!empty($search_data['name'])) {
            $teacher->andWhere(['like', 'name', $search_data['name']]);
        }
        if (!empty($search_data['tel'])) {
            $teacher->andWhere(['like', 'mobile', $search_data['tel']]);
        }
        if (!empty($search_data['mechanic_name'])) {
            $ids = Mechanic::find()->select('id')->where(['like','name',$search_data['mechanic_name']])->column();
            $teacher->andWhere(['mechanic_id'=>$ids]);
        }
        if ($mids) {
            $teacher->andWhere(['mechanic_id' => $mids]);
        }
        if(isset(\Yii::$app->user->identity)&&\Yii::$app->user->identity->role == 'class_director') {
            $admin_id = \Yii::$app->user->id;
            $mechanic_id = Mechanic::find()->select('id')->where(['admin_id'=>$admin_id,'is_delete'=>0])->column();
            $teacher->andWhere(['mechanic_id' => $mechanic_id]);
        }
        if(isset(\Yii::$app->user->identity->role) && \Yii::$app->user->identity->role == 'category'){
            $teacher->andWhere(['cate_id'=>\Yii::$app->user->identity->type_id]);
        }
        $pages = new Pagination(['totalCount' => $teacher->count(), 'pageSize' => 14, 'params' => array_merge($_GET, $search_data)]);
        $teacher = $teacher->offset($pages->offset)->limit($pages->limit)->all();
        $model = Fun::asArray($teacher, ['mechanic_name', 'deleteHandle']);
        return $this->render('index', ['model' => $model, 'form' => $search_form, 'pages' => $pages]);
    }

    /*
     * 老师添加
     */
    public function actionCreate()
    {
        $mids = Fun::getMechanicIds(); //获取机构以及子机构id
        $model = new Teacher();
        $model->scenario = 'create';
        $model->status = 1;
        $mechanicModel = Mechanic::find()->where(['site_id' => Fun::getSiteId(), 'is_delete' => 0, 'status' => 1]);
        if (!empty($mids)) {
            $mechanicModel->andWhere(['id' => $mids]);//这个地方是如果是有机构id传过来，那么可以选择的有当前的机构或者是找个机构的子类
        }
        $mechanic = $mechanicModel->indexBy('id')->all();
        if (count($mechanic) == 1) {
            foreach ($mechanic as $key => $val) {
                $model->mechanic_id = $key;
            }
            $tree_mechanic = ArrayHelper::map($mechanic, 'id', 'name');
        } else {
            $tree_mechanic = (new Tree($mechanic))->get_tree_select();
        }
        $cate = Cate::find()->where(['is_show' => 1, 'is_delete' => 0])->indexBy('id')->all();
        $tree_cate = (new Tree($cate))->get_tree_select();
        $now_year = (int)date('Y');
        $oldyear = $now_year - 100;
        $years = range($oldyear, $now_year);
        $year = [];
        foreach ($years as $y) {
            $year[$y] = $y;
        }

//        $navModel = NavMenu::find()->where(['type'=>'teacher']);
//        if(isset(\Yii::$app->user->identity->type_id)){
//            $navModel->andWhere(['type_id'=>\Yii::$app->user->identity->type_id]);
//        }
//        $datamenu = $navModel->all();
//        $menu = [];
//        if($datamenu != null){
//            foreach ($datamenu as $val){
//                if($val->type_id == 1){
//                    $typename = '益智';
//                }elseif ($val->type_id == 2){
//                    $typename = '音乐';
//                }else{
//                    $typename = '形体';
//                }
//                $menu[$val->id] = $val['name'].'-'.$typename;
//            }
//        }
        $cate_checked = [];
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $post = \Yii::$app->request->post();
            $model->site_id = Fun::getSiteId();
            $model->isrecommend = 1;
            $mechanicModel = Mechanic::findOne($model->mechanic_id);
            $model->parent_id = $mechanicModel->admin_id;  //教服id
            $model->headmaster_account = $model->mobile . '_t';
            if ($model->save(false)) {
                $cate_id = array_unique($post['Teacher']['teach_cates']);
                foreach ($cate_id as $k => $v) {
                    $cate_relation = new CateRelation();
                    $cate_relation->object_id = $model->id;
                    $cate_relation->cate_id = $v;
                    $cate_relation->type = 1;
                    $cate_relation->save(false);
                }
                return $this->redirectMessage('添加成功', Fun::url(['teacher/index']));
            }
        }
        return $this->render('create', ['model' => $model, 'cate' => $tree_cate, 'cate_checked' => $cate_checked, 'mechanic' => $tree_mechanic, 'year' => $year]);
    }

    public function actionUpdate()
    {
        $id = \Yii::$app->request->get('id');
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $model = Teacher::findOne($id);
        if ($model === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
//        if(isset(\Yii::$app->user->identity->role) && \Yii::$app->user->identity->role == 'category'){
//            if($model->cate_id != \Yii::$app->user->identity->type_id){
//                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '没权限'), 404);
//            }
//        }
//        $model->scenario = 'create';
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        $mids = Fun::getMechanicIds(); //获取机构以及子机构id
        $mechanicModel = Mechanic::find()->where(['site_id' => Fun::getSiteId(), 'is_delete' => 0, 'status' => 1]);
        if (!empty($mids)) {
            $mechanicModel->andWhere(['id' => $mids]);
        }
        $mechanic = $mechanicModel->indexBy('id')->all();
        $tree_mechanic = (new Tree($mechanic))->get_tree_select();
        $cate = Cate::find()->where(['is_show' => 1, 'is_delete' => 0])->indexBy('id')->all();
        $tree_cate = (new Tree($cate))->get_tree_select();
        $cate_check = CateRelation::find()->where(['object_id' => $id,'type'=>1])->all();
        $cate_checked = [];
        foreach ($cate_check as $k => $v) {
            $cate = Cate::findOne([$v->cate_id]);
            $cate_checked[$v->cate_id] = $cate->name;
        }
        $now_year = (int)date('Y');
        $oldyear = $now_year - 100;
        $years = range($oldyear, $now_year);
        $year = [];
        foreach ($years as $y) {
            $year[$y] = $y;
        }
//        $navModel = NavMenu::find()->where(['type'=>'teacher']);
//        if(isset(\Yii::$app->user->identity->type_id)){
//            $navModel->andWhere(['type_id'=>\Yii::$app->user->identity->type_id]);
//        }
//        $datamenu = $navModel->all();
//        $menu = [];
//        if($datamenu != null){
//            foreach ($datamenu as $val){
//                if($val->type_id == 1){
//                    $typename = '益智';
//                }elseif ($val->type_id == 2){
//                    $typename = '音乐';
//                }else{
//                    $typename = '形体';
//                }
//                $menu[$val->id] = $val['name'].'-'.$typename;
//            }
//        }
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $post = \Yii::$app->request->post();
            //若班主任更改，则cate_id变更为新班主任的cate_id
            $model->headmaster_account = $model->mobile . '_t';
            $mechanicModel = Mechanic::findOne($model->mechanic_id);
            $model->parent_id = $mechanicModel->admin_id;  //教服id
            if ($model->save(false)) {
                CateRelation::deleteAll(['and','object_id=:id','type=:type'], [':id' => $model->id,':type'=>1]);
                $cate_id = array_unique($post['Teacher']['teach_cates']);
                foreach ($cate_id as $k => $v) {
                    $cate_relation = new CateRelation();
                    $cate_relation->object_id = $model->id;
                    $cate_relation->cate_id = $v;
                    $cate_relation->type = 1;
                    $cate_relation->save(false);
                }
                return $this->redirectMessage('修改成功', Fun::url(['teacher/index']));
            }
        }
        return $this->render('create', ['model' => $model, 'cate' => $tree_cate, 'cate_checked' => $cate_checked, 'mechanic' => $tree_mechanic,  'year' => $year,]);
    }

    public function actions()
    {
        return [
            'delete' => [
                'class' => DeleteAction::className(),
                'modelClass' => Teacher::className(),
                'message' => ['success' => '删除成功！'],
                'redirectTo' => 'teacher/index',
            ],
        ];
    }

    public function actionGetheadmaster()
    {
        if (\Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $headmaster = Headmaster::find()->where(['mechanic_id' => \Yii::$app->request->post('mechanic_id'), 'status' => 1])->asArray()->all();
            foreach ($headmaster as $k => $v) {
                $cate_name = [];
                switch ($v['cate_id']) {
                    case 1:
                        $cate_name = '益智';
                        break;
                    case 2:
                        $cate_name = '音乐';
                        break;
                    case 3:
                        $cate_name = '形体';
                        break;
                }
                $v['name'] = $v['name'] . "-" . $cate_name;
            }
            $data = [
                'headmaster' => $headmaster,
            ];
            return $data;
        }
    }


}
